package p2pcdnsim.network;


import desmoj.core.simulator.Model;


public class NetworkLayer {
	
	private NetworkAddress address;
	private Node node;
	private RouterTable rTable;
	private Model model;


	TransportLayer transportLayer;

	public NetworkLayer(Model owner) {
		this.model = owner;
		this.node = null;
		this.rTable = null;
		this.transportLayer=null;
		this.address = null;
	}

	public NetworkAddress getDefaultAddress() {
		return address;
	}

	public void addPacket(Packet p) {
		//System.out.println("Node "+this.node.getName()+": pcaket added "+p.getId()+" at "+(this.currentTime().getTimeValue())+" to "+p.getDestination());
		if(p.getDestination().equals(this.address)) {
			this.receivePacket(p);
		} else if(p.getDestination().isClientAddress() && p.getDestination().getRouterAddress().equals(this.address)) {
			((RouterNode)node).getLinkBus().sendPacket(p);
		} else {
				//System.out.println("Node "+this.node.getNodeId()+": routing packet "+p.getId()+" at "+this.currentTime().getTimeValue());
			Link link;
			if(rTable != null) {
				//Multiple links
				link = rTable.getLink(p.getDestination().getRouterAddress());
			} else {
				//Default
				link = node.getDefaultLink();
			}
			link.sendPacket(p);
		}
	}

	private void receivePacket(Packet p) {
		this.transportLayer.receiveDatagram((Datagram)p.getContent());
	}

	public void setNode(Node node) {
		this.node = node;
	}

	public void setRouterTable(RouterTable t) {
		this.rTable = t;
	}
	
	public RouterTable getRouterTable() {
		return rTable;
	}

	public void setTransportLayer(TransportLayer transportLayer) {
		this.transportLayer = transportLayer;
		transportLayer.setNetworkLayer(this);
		
	}

	public TransportLayer getTransportLayer() {
		return this.transportLayer;
		
	}

	public void setNetworkAddress(NetworkAddress address) {
		this.address = address;
		
	}

	public Model getModel() {
		return model;
	}

}
